// $Id: GoogleConnector.java 6 2007-11-28 07:57:36Z joakim.waltersson $
package se.waltersson.wowarmory.example;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.media.MediaService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.util.AuthenticationException;

/**
 * @author Joakim Waltersson
 * @version $Revision: 6 $ $Date: 2007-11-28 07:57:36 +0000 (Wed, 28 Nov 2007) $
 */
public class GoogleConnector {

    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 2) {
            printUsage();
            System.exit(0);
        }
        String user = args[0];
        String password = args[1];
        if (args.length == 2) {
            listSpreadsheets(user, password);
        } else {
            String documentId = args[2];
            updateSpreadsheet(user, password, documentId);
        }
    }

    private static void updateSpreadsheet(String user, String password,
                                          String documentId)
    {
        // TODO Auto-generated method stub
        
    }

    private static void listSpreadsheets(String user, String password) {
        URL feedUrl;
        try {
            feedUrl = new URL("http://spreadsheets.google.com/feeds/" +
                        "spreadsheets/private/full");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return;
        }
        MediaService myService = new MediaService("wise",
            "waltersson-wowarmorysync-0.1");
        try {
            myService.setUserCredentials(user, password);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        // Mark the feed as an Document List feed:
        new DocumentListFeed().declareExtensions(myService
            .getExtensionProfile());
        DocumentListFeed f;
        try {
            f = myService.getFeed(feedUrl, DocumentListFeed.class);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        List<DocumentListEntry> docs = f.getEntries();
        for (DocumentListEntry doc : docs) {
            System.out.println(doc.getId() + ": " + doc.getTitle()
                .getPlainText());
        }
    }

    private static void printUsage() {
        System.out.println("Usage: java GoogleConnector googleaccount" +
        		" password [\"document title\"|documentId]");
    }

}
